<template>
  <div class="knowledge-stages-container">
    <el-card>
      <template #header>
        <div class="page-header">
          <div class="breadcrumb-section">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item @click="goBack" class="clickable">技术方向管理</el-breadcrumb-item>
              <el-breadcrumb-item @click="goToKnowledgePoints" class="clickable">
                {{ nodeInfo.categoryName }}
              </el-breadcrumb-item>
              <el-breadcrumb-item>{{ nodeInfo.nodeName }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="openStageDialog(false)">
              <el-icon><Plus /></el-icon>
              新增关卡
            </el-button>
          </div>
        </div>
      </template>

      <div class="node-info-bar">
        <div class="node-overview">
          <div class="node-icon">
            <span>💡</span>
          </div>
          <div class="node-details">
            <h2 class="node-name">{{ nodeInfo.nodeName }}</h2>
            <div class="node-stats">
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <span>难度：{{ nodeInfo.difficulty }}/5</span>
              </div>
              <div class="stat-item">
                <el-icon><Flag /></el-icon>
                <span>共{{ stages.length }}关</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="filter-bar">
        <div class="filter-group">
          <div class="filter-item">
            <span class="label">类型筛选：</span>
            <el-select v-model="filterType" placeholder="全部类型" clearable style="width: 150px">
              <el-option label="全部类型" value="" />
              <el-option label="练习关卡" value="practice" />
              <el-option label="考试关卡" value="exam" />
              <el-option label="挑战关卡" value="challenge" />
              <el-option label="项目关卡" value="project" />
              <el-option label="综合关卡" value="mixed" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="label">难度筛选：</span>
            <el-select v-model="filterDifficulty" placeholder="全部难度" clearable style="width: 120px">
              <el-option label="全部难度" value="" />
              <el-option label="1星" :value="1" />
              <el-option label="2星" :value="2" />
              <el-option label="3星" :value="3" />
              <el-option label="4星" :value="4" />
              <el-option label="5星" :value="5" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="label">搜索：</span>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索关卡名称或描述"
              clearable
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
        <div class="view-mode">
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button label="timeline">时间轴</el-radio-button>
            <el-radio-button label="list">列表</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 时间轴视图 -->
      <div v-if="viewMode === 'timeline'" class="stages-timeline">
        <div 
          v-for="(stage, index) in filteredStages" 
          :key="stage.id"
          class="stage-timeline-item"
        >
          <div class="stage-connector" v-if="index > 0"></div>
          <div class="stage-timeline-card">
            <div class="stage-timeline-header">
              <div class="stage-number">{{ stage.stageNumber }}</div>
              <div class="stage-actions">
                <el-dropdown @command="handleStageCommand">
                  <el-button type="text" size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{action: 'edit', stage: stage}">
                        <el-icon><Edit /></el-icon>
                        编辑关卡
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'copy', stage: stage}">
                        <el-icon><CopyDocument /></el-icon>
                        复制关卡
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'delete', stage: stage}" class="danger-item">
                        <el-icon><Delete /></el-icon>
                        删除关卡
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>

            <div class="stage-timeline-body">
              <h3 class="stage-name">{{ stage.stageName }}</h3>
              <p class="stage-description">{{ stage.description || '暂无描述' }}</p>
              
              <div class="stage-meta">
                <div class="meta-row">
                  <el-tag :type="getTypeTagType(stage.stageType)" size="small">
                    {{ getTypeText(stage.stageType) }}
                  </el-tag>
                  <div class="difficulty-stars">
                    <el-rate v-model="stage.difficultyLevel" disabled size="small" />
                  </div>
                  <div class="tags" v-if="stage.tags && stage.tags.length">
                    <el-tag v-for="tag in stage.tags" :key="tag" size="small" type="info">
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
                
                <div class="meta-stats">
                  <div class="stat-item" v-if="stage.estimatedTime">
                    <el-icon><Clock /></el-icon>
                    <span>{{ stage.estimatedTime }}分钟</span>
                  </div>
                  <div class="stat-item" v-if="stage.totalQuestions">
                    <el-icon><EditPen /></el-icon>
                    <span>{{ stage.totalQuestions }}题</span>
                  </div>
                  <div class="stat-item" v-if="stage.rewardPoints">
                    <el-icon><Trophy /></el-icon>
                    <span>{{ stage.rewardPoints }}积分</span>
                  </div>
                  <div class="stat-item" v-if="stage.rewardExp">
                    <el-icon><Medal /></el-icon>
                    <span>{{ stage.rewardExp }}经验</span>
                  </div>
                </div>

                <div class="pass-conditions" v-if="stage.passCondition">
                  <div class="condition-title">通关条件：</div>
                  <div class="condition-items">
                    <span v-if="stage.passCondition.min_score" class="condition-item">
                      得分≥{{ stage.passCondition.min_score }}分
                    </span>
                    <span v-if="stage.passCondition.min_correct_rate" class="condition-item">
                      正确率≥{{ Math.round(stage.passCondition.min_correct_rate * 100) }}%
                    </span>
                    <span v-if="stage.passCondition.time_limit" class="condition-item">
                      时限{{ Math.floor(stage.passCondition.time_limit / 60) }}分钟
                    </span>
                  </div>
                </div>
              </div>
            </div>

            <div class="stage-timeline-footer">
              <el-button type="success" size="small" @click="goToQuestions(stage)">
                <el-icon><EditPen /></el-icon>
                管理题目
              </el-button>
              <el-button type="primary" size="small" @click="openStageDialog(true, stage)">
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="confirmDeleteStage(stage)">
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 添加新关卡 -->
        <div class="stage-timeline-item add-stage-item" v-if="canAddStage">
          <div class="stage-connector"></div>
          <div class="add-stage-card" @click="openStageDialog(false)">
            <el-icon class="add-icon"><Plus /></el-icon>
            <h3>添加新关卡</h3>
            <p>第 {{ stages.length + 1 }} 关</p>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="stages-table">
        <el-table :data="filteredStages" stripe>
          <el-table-column prop="stageNumber" label="序号" width="80" />
          <el-table-column prop="stageName" label="关卡名称" min-width="200" />
          <el-table-column prop="stageType" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.stageType)" size="small">
                {{ getTypeText(row.stageType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="difficultyLevel" label="难度" width="120">
            <template #default="{ row }">
              <el-rate v-model="row.difficultyLevel" disabled size="small" />
            </template>
          </el-table-column>
          <el-table-column prop="estimatedTime" label="预计时长" width="100">
            <template #default="{ row }">
              <span v-if="row.estimatedTime">{{ row.estimatedTime }}分钟</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalQuestions" label="题目数" width="80" />
          <el-table-column prop="rewardPoints" label="奖励积分" width="80" />
          <el-table-column label="操作" width="290" fixed="right">
            <template #default="{ row }">
              <el-button type="success" size="small" @click="goToQuestions(row)">管理题目</el-button>
              <el-button type="primary" size="small" @click="openStageDialog(true, row)">编辑</el-button>
              <el-button type="warning" size="small" @click="copyStage(row)">复制</el-button>
              <el-popconfirm title="确定删除此关卡吗？" @confirm="deleteStage(row)">
                <template #reference>
                  <el-button type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 关卡编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑关卡' : '新增关卡'"
      width="900px"
      @closed="resetForm"
    >
      <el-form 
        ref="formRef" 
        :model="stageForm" 
        :rules="formRules" 
        label-width="120px"
        label-position="left"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关卡标识" prop="stageKey">
              <el-input v-model="stageForm.stageKey" placeholder="请输入关卡唯一标识">
                <template #prepend>stage_</template>
              </el-input>
              <div class="form-tip">只能包含字母、数字和下划线</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关卡名称" prop="stageName">
              <el-input v-model="stageForm.stageName" placeholder="请输入关卡名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="关卡序号" prop="stageNumber">
              <el-input-number 
                v-model="stageForm.stageNumber" 
                :min="1" 
                :max="100"
                placeholder="关卡序号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关卡类型" prop="stageType">
              <el-select v-model="stageForm.stageType" placeholder="请选择关卡类型" style="width: 100%">
                <el-option label="练习关卡" value="practice" />
                <el-option label="考试关卡" value="exam" />
                <el-option label="挑战关卡" value="challenge" />
                <el-option label="项目关卡" value="project" />
                <el-option label="综合关卡" value="mixed" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度等级" prop="difficultyLevel">
              <el-rate v-model="stageForm.difficultyLevel" :max="5" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="关卡描述">
          <el-input 
            v-model="stageForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入关卡描述，说明学习内容和目标"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="预计时间" prop="estimatedTime">
              <el-input-number 
                v-model="stageForm.estimatedTime" 
                :min="0"
                placeholder="分钟"
                style="width: 100%"
              />
              <div class="form-tip">预计完成时间（分钟）</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="题目总数" prop="totalQuestions">
              <el-input-number 
                v-model="stageForm.totalQuestions" 
                :min="0"
                placeholder="题目数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最少答题数" prop="minQuestions">
              <el-input-number 
                v-model="stageForm.minQuestions" 
                :min="0"
                :max="stageForm.totalQuestions || 100"
                placeholder="最少答题数"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="通关条件">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input-number 
                v-model="stageForm.passCondition.min_score"
                :min="0"
                :max="100"
                placeholder="最低分数"
                style="width: 100%"
              />
              <div class="form-tip">最低分数（0-100分）</div>
            </el-col>
            <el-col :span="8">
              <el-input-number 
                v-model="stageForm.passCondition.min_correct_rate"
                :min="0"
                :max="1"
                :step="0.05"
                :precision="2"
                placeholder="最低正确率"
                style="width: 100%"
              />
              <div class="form-tip">最低正确率（0-1）</div>
            </el-col>
            <el-col :span="8">
              <el-input-number 
                v-model="stageForm.passCondition.time_limit"
                :min="0"
                placeholder="时间限制"
                style="width: 100%"
              />
              <div class="form-tip">时间限制（秒）</div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="奖励积分">
              <el-input-number 
                v-model="stageForm.rewardPoints" 
                :min="0"
                placeholder="通关奖励积分"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="奖励经验">
              <el-input-number 
                v-model="stageForm.rewardExp" 
                :min="0"
                placeholder="通关奖励经验值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大尝试次数">
              <el-input-number 
                v-model="stageForm.maxAttempts" 
                :min="1"
                placeholder="最大尝试次数"
                style="width: 100%"
              />
              <div class="form-tip">留空表示无限制</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="关卡标签">
              <el-select
                v-model="stageForm.tags"
                multiple
                filterable
                allow-create
                placeholder="选择或输入标签"
                style="width: 100%"
              >
                <el-option
                  v-for="tag in availableTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他设置">
              <div class="checkbox-group">
                <el-checkbox v-model="stageForm.isAdaptive">自适应难度</el-checkbox>
                <el-checkbox v-model="stageForm.isActive">启用状态</el-checkbox>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitStage">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { 
  Plus, Star, Clock, Flag, Search, Edit, Delete, More, 
  EditPen, Trophy, Medal, CopyDocument
} from '@element-plus/icons-vue'
import { get } from '@/axios'

const route = useRoute()
const router = useRouter()

// 从路由参数获取知识节点信息
const nodeInfo = reactive({
  nodeId: route.query.pointId || 1,
  nodeKey: route.query.pointKey || 'js_basics',
  nodeName: route.query.pointName || 'JavaScript基础知识',
  categoryId: route.query.categoryId || 1,
  categoryName: route.query.categoryName || 'JavaScript开发',
  difficulty: parseInt(route.query.difficulty) || 3
})

// 响应式数据
const stages = ref([])
const filterType = ref('')
const filterDifficulty = ref('')
const searchKeyword = ref('')
const viewMode = ref('timeline')
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const formRef = ref()

// 可用标签
const availableTags = ref([
  '基础', '进阶', '实战', '理论', '实践', '核心概念', 
  '语法', 'API', '框架', '库', '工具', '调试',
  '性能', '安全', '最佳实践', '设计模式'
])

// 关卡表单数据
const stageForm = reactive({
  id: null,
  node_id: nodeInfo.nodeId,
  stageKey: '',
  stageName: '',
  stageNumber: 1,
  stageType: 'practice',
  difficultyLevel: 1,
  description: '',
  passCondition: {
    min_score: 60,
    min_correct_rate: 0.6,
    time_limit: 1800
  },
  rewardPoints: 10,
  rewardExp: 5,
  estimatedTime: 30,
  totalQuestions: 10,
  minQuestions: 8,
  maxAttempts: null,
  isAdaptive: false,
  isActive: true,
  tags: []
})

// 表单验证规则
const formRules = {
  stageKey: [
    { required: true, message: '请输入关卡标识', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  stageName: [
    { required: true, message: '请输入关卡名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  stageNumber: [
    { required: true, message: '请输入关卡序号', trigger: 'change' },
    { type: 'number', min: 1, max: 100, message: '关卡序号必须在1-100之间', trigger: 'change' }
  ],
  stageType: [
    { required: true, message: '请选择关卡类型', trigger: 'change' }
  ],
  difficultyLevel: [
    { required: true, message: '请选择难度等级', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '难度等级必须在1-5之间', trigger: 'change' }
  ],
  estimatedTime: [
    { type: 'number', min: 1, message: '预计时间必须大于0', trigger: 'change' }
  ],
  totalQuestions: [
    { type: 'number', min: 1, message: '题目总数必须大于0', trigger: 'change' }
  ]
}

const goToQuestions = (stage) => {
  router.push({
    path: '/questions/knowledge/stages/examination',  // 跳转到题目管理页面
    query: {
      stageId: stage.id,              // 关卡ID
      stageKey: stage.stageKey,      // 关卡标识
      stageName: stage.stageName,    // 关卡名称
      stageNumber: stage.stageNumber, // 关卡序号
      nodeId: nodeInfo.nodeId,        // 知识节点ID
      nodeName: nodeInfo.nodeName,    // 知识节点名称
      categoryId: nodeInfo.categoryId, // 分类ID
      categoryName: nodeInfo.categoryName // 分类名称
    }
  })
}

// 计算属性
const filteredStages = computed(() => {
  let filtered = stages.value.filter(stage => !stage.is_deleted)
  
  // 按类型筛选
  if (filterType.value) {
    filtered = filtered.filter(stage => stage.stageType === filterType.value)
  }
  
  // 按难度筛选
  if (filterDifficulty.value) {
    filtered = filtered.filter(stage => stage.difficultyLevel === filterDifficulty.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(stage => 
      stage.stageName?.toLowerCase().includes(keyword) ||
      (stage.description && stage.description.toLowerCase().includes(keyword)) ||
      stage.stageKey?.toLowerCase().includes(keyword) ||
      (stage.tags && stage.tags.some(tag => tag.toLowerCase().includes(keyword)))
    )
  }
  
  return filtered.sort((a, b) => a.stageNumber - b.stageNumber)
})

const canAddStage = computed(() => {
  return stages.value.length < 50 // 限制最多50关
})

fetchStages()
function fetchStages(){
  get('/umsAdmin/getStage',{nodeId:nodeInfo.nodeId},content=>{
    const processedStages = content.map(stage => {
      if (stage.passCondition && typeof stage.passCondition === 'string') {
        try {
          stage.passCondition = JSON.parse(stage.passCondition);
        } catch (error) {
          console.error('解析passCondition失败:', error);
          stage.passCondition = {};
        }
      }
      return stage;
    });
    stages.value = content
    stages.passCondition = processedStages
  })
}

// 方法
const goBack = () => {
  router.push('/questions')
}

const goToKnowledgePoints = () => {
  router.push({
    path: '/questions/knowledge',
    query: {
      categoryId: nodeInfo.categoryId,
      categoryKey: route.query.categoryKey,
      categoryName: nodeInfo.categoryName
    }
  })
}

const getTypeTagType = (type) => {
  const types = {
    'practice': 'success',
    'exam': 'danger',
    'challenge': 'warning',
    'project': 'primary',
    'mixed': 'info'
  }
  return types[type] || 'info'
}

const getTypeText = (type) => {
  const texts = {
    'practice': '练习关卡',
    'exam': '考试关卡', 
    'challenge': '挑战关卡',
    'project': '项目关卡',
    'mixed': '综合关卡'
  }
  return texts[type] || type
}

const openStageDialog = (edit, stage = null) => {
  isEdit.value = edit
  if (edit && stage) {
    Object.assign(stageForm, {
      ...stage,
      passCondition: { ...stage.passCondition },
      tags: [...(stage.tags || [])]
    })
  } else {
    resetForm()
    stageForm.stageNumber = stages.value.length + 1
  }
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(stageForm, {
    id: null,
    node_id: nodeInfo.nodeId,
    stageKey: '',
    stageName: '',
    stageNumber: 1,
    stageType: 'practice',
    difficultyLevel: 1,
    description: '',
    passCondition: {
      min_score: 60,
      min_correct_rate: 0.6,
      time_limit: 1800
    },
    rewardPoints: 10,
    rewardExp: 5,
    estimatedTime: 30,
    totalQuestions: 10,
    minQuestions: 8,
    maxAttempts: null,
    isAdaptive: false,
    isActive: true,
    tags: []
  })
  formRef.value?.resetFields()
}

const submitStage = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const stageData = {
      ...stageForm,
      create_time: new Date().toLocaleString(),
      update_time: new Date().toLocaleString()
    }
    
    if (isEdit.value) {
      const index = stages.value.findIndex(s => s.id === stageForm.id)
      if (index !== -1) {
        stages.value[index] = { ...stageData }
      }
      ElMessage.success('关卡更新成功')
    } else {
      stageData.id = Date.now() // 模拟生成ID
      stages.value.push(stageData)
      ElMessage.success('关卡创建成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleStageCommand = ({ action, stage }) => {
  switch (action) {
    case 'edit':
      openStageDialog(true, stage)
      break
    case 'copy':
      copyStage(stage)
      break
    case 'delete':
      confirmDeleteStage(stage)
      break
  }
}

const copyStage = (stage) => {
  const newStage = {
    ...stage,
    id: Date.now(),
    stageKey: stage.stageKey + '_copy',
    stageName: stage.stageName + ' (副本)',
    stageNumber: stages.value.length + 1,
    create_time: new Date().toLocaleString(),
    update_time: new Date().toLocaleString()
  }
  
  stages.value.push(newStage)
  ElMessage.success('关卡复制成功')
}

const confirmDeleteStage = (stage) => {
  ElMessageBox.confirm(
    `确定要删除关卡"${stage.stageName}"吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteStage(stage)
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const deleteStage = (stage) => {
  const index = stages.value.findIndex(s => s.id === stage.id)
  if (index !== -1) {
    stages.value.splice(index, 1)
    ElMessage.success('关卡删除成功')
  }
}

onMounted(() => {
  console.log('路由参数：', route.query)
  console.log('节点信息：', nodeInfo)
  fetchStages()
})
</script>

<style scoped>
.knowledge-stages-container {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.knowledge-stages-container .el-card {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.breadcrumb-section .clickable {
  cursor: pointer;
  color: #409eff;
  transition: all 0.3s ease;
}

.breadcrumb-section .clickable:hover {
  text-decoration: underline;
  transform: translateX(2px);
}

.node-info-bar {
  margin: 20px 0;
  padding: 24px;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border-radius: 16px;
  color: white;
}

.node-overview {
  display: flex;
  align-items: center;
  gap: 24px;
}

.node-icon span {
  font-size: 48px;
  display: block;
}

.node-details {
  flex: 1;
}

.node-name {
  margin: 0 0 12px 0;
  font-size: 28px;
  font-weight: bold;
}

.node-stats {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  opacity: 0.9;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 24px 0;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 12px;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-group {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item .label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.view-mode {
  display: flex;
  align-items: center;
}

/* 时间轴视图样式 */
.stages-timeline {
  position: relative;
  padding: 20px 0;
}

.stage-timeline-item {
  position: relative;
  margin-bottom: 40px;
  padding-left: 80px;
}

.stage-timeline-item:nth-child(even) {
  padding-left: 0;
  padding-right: 80px;
  text-align: right;
}

.stage-timeline-item:nth-child(even) .stage-timeline-card {
  margin-left: auto;
}

.stage-connector {
  position: absolute;
  left: 50%;
  top: -40px;
  width: 2px;
  height: 40px;
  background: linear-gradient(to bottom, #e6a23c, #409eff);
  transform: translateX(-50%);
}

.stage-timeline-card {
  max-width: 500px;
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border: 2px solid #e4e7ed;
}

.stage-timeline-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

.stage-timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.stage-number {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #409eff 0%, #36b9cc 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
  position: absolute;
  left: 50%;
  top: 20px;
  transform: translateX(-50%);
}

.stage-timeline-item:nth-child(even) .stage-number {
  left: 50%;
}

.stage-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stage-timeline-card:hover .stage-actions {
  opacity: 1;
}

.stage-timeline-body {
  margin-bottom: 16px;
}

.stage-name {
  margin: 0 0 12px 0;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.stage-description {
  margin: 0 0 16px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
}

.stage-meta {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.meta-row {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.meta-stats {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.meta-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: #606266;
}

.pass-conditions {
  background: rgba(64, 158, 255, 0.1);
  padding: 12px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.condition-title {
  font-size: 13px;
  color: #409eff;
  font-weight: bold;
  margin-bottom: 8px;
}

.condition-items {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.condition-item {
  font-size: 12px;
  color: #606266;
  background: white;
  padding: 4px 8px;
  border-radius: 4px;
}

.stage-timeline-footer {
  display: flex;
  gap: 8px;
}

/* 添加关卡项样式 */
.add-stage-item .add-stage-card {
  max-width: 300px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 16px;
  padding: 40px 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px dashed rgba(255, 255, 255, 0.3);
}

.add-stage-item .add-stage-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(102, 126, 234, 0.3);
  border-color: rgba(255, 255, 255, 0.6);
}

.add-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.8;
}

.add-stage-card h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.add-stage-card p {
  margin: 0;
  font-size: 14px;
  opacity: 0.8;
}

/* 网格视图样式 */
.stages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  padding: 20px 0;
}

.stage-grid-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  transition: all 0.3s ease;
  border: 2px solid #e4e7ed;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stage-grid-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

.grid-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.grid-card-header .stage-number {
  position: relative;
  transform: none;
  left: auto;
  top: auto;
  width: 40px;
  height: 40px;
  font-size: 16px;
}

.grid-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.stage-grid-card:hover .grid-actions {
  opacity: 1;
}

.grid-card-body .stage-name {
  font-size: 18px;
  margin-bottom: 8px;
}

.grid-card-body .stage-description {
  font-size: 13px;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.grid-card-footer {
  display: flex;
  justify-content: center;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 添加关卡网格卡片 */
.stage-grid-card.add-stage-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: 2px dashed rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  cursor: pointer;
}

.add-stage-content {
  text-align: center;
}

.add-stage-content .add-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.add-stage-content h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.add-stage-content p {
  margin: 0;
  font-size: 14px;
  opacity: 0.8;
}

/* 列表视图样式 */
.stages-table {
  padding: 20px 0;
}

/* 对话框样式 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.danger-item {
  color: #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .knowledge-stages-container {
    padding: 10px;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group {
    flex-direction: column;
    gap: 12px;
  }
  
  .filter-item {
    width: 100%;
  }
  
  .stages-grid {
    grid-template-columns: 1fr;
  }
  
  .stage-timeline-item {
    padding-left: 0;
    padding-right: 0;
    text-align: left;
  }
  
  .stage-timeline-item:nth-child(even) {
    padding-left: 0;
    padding-right: 0;
    text-align: left;
  }
  
  .stage-timeline-item:nth-child(even) .stage-timeline-card {
    margin-left: 0;
  }
  
  .stage-timeline-card {
    max-width: none;
  }
  
  .stage-number {
    left: 24px !important;
  }
  
  .stage-connector {
    left: 49px !important;
  }
}

@media (max-width: 480px) {
  .node-overview {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .node-stats {
    justify-content: center;
  }
  
  .stage-timeline-item {
    padding-left: 80px;
  }
  
  .meta-row, .meta-stats, .condition-items {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>